local UpdateManager = class("UpdateManager")
local GameUtils = require("utils.GameUtils")
local Signal = require("event.Signal")
local HeartBeatService = require("manager.HeartBeatService")

function UpdateManager:ctor()
    local gameObject = GameUtils.InstantiateEmptyObject("UpdateManager")
    local behaviour = gameObject:AddComponent(typeof(CS.UpdateBehaviour))
    behaviour:SetScriptEnv(self)
    self._signal = Signal.new()
    self._heartBeatService = HeartBeatService.new()
    self._addList = {}
    self._removeList = {}
    self._behaviourList = {}
end

function UpdateManager:addBehaviour(behaviour)
    table.insert(self._addList, behaviour)
end

function UpdateManager:removeBehaviour(behaviour)
    table.insert(self._removeList, behaviour)
end

function UpdateManager:update()
    self:_addBehaviourList()
    self:_removeBehaviourList()
    local dt = G_Time.deltaTime
    for behaviour, _ in pairs(self._behaviourList) do
        if behaviour.enabled then
            if behaviour.update then
                behaviour:update(dt)
            end
        end
    end
    for behaviour, _ in pairs(self._behaviourList) do
        if behaviour.enabled then
            if behaviour.lateUpdate then
                behaviour:lateUpdate(dt)
            end
        end
    end
    self:_addBehaviourList()
    self:_removeBehaviourList()
    self._heartBeatService:update(dt)
end

function UpdateManager:_addBehaviourList()
    for i = 1, #self._addList do
        self._behaviourList[self._addList[i]] = true
    end
    self._addList = {}
end

function UpdateManager:_removeBehaviourList()
    for i = 1, #self._removeList do
        self._behaviourList[self._removeList[i]] = nil
    end
    self._removeList = {}
end

function UpdateManager:addUpadateEvent(listener, once)
    return self._signal:registerListener(listener, 1, once)
end

function UpdateManager:removeUpdateEvent(event)
    self._signal:remove(event)
end

function UpdateManager:onDestroy()
end

function UpdateManager:onApplicationQuit()
    G_UserData:clear()
    G_StoreManager:save()
    printDebug("onApplicationQuit")
end

return UpdateManager
